const { Model, Schema } = require('../helps/model');
const { formatData } = require('../helps/tools');
// const { executor } = require('../helps/model');

// CREATE TABLE `user_chat` (
//   `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//   `robot_id` int(11) unsigned NOT NULL COMMENT '机器人id',
//   `user_id` int(11) unsigned NOT NULL COMMENT '用户id',
//   `type` tinyint(1) unsigned NOT NULL COMMENT '消息类型：1文字，2表情，3音频',
//   `direction` tinyint(1) unsigned NOT NULL COMMENT '方向：1、机器人，2、用户',
//   `content` text COMMENT '聊天内容',
//   `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
//   `delete_time` datetime,
//   PRIMARY KEY (`id`),
//   KEY `robotd` (`robot_id`, `user_id`) USING BTREE
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户聊天表';

const schema = new Schema({
  primary: 'id',
  create_time: true,
  soft_delete: true,
  auto_increment: true,
  fields: ['id', 'robot_id', 'user_id', 'type', 'content', 'direction'],
  default: {
    content: '',
    type: 0,
  },
});

export const model = new Model('user_chat', schema);

/**
 * 查找
 * @param id
 * @returns {*}
 */
export function get(id) {
  return model.findByKey(id);
}

/**
 * 查找列表
 * @param ids
 * @returns {*}
 */
export function getIds(ids) {
  return model.findByQuery({
    where: [
      ['id', 'in', ids],
    ],
  });
}

/**
 * 创建
 * @param data
 * @returns {*}
 */
export function add(data) {
  return model.insert(formatData(schema.baseFields(), data));
}

/**
 * 更新
 * @param id
 * @param data
 * @returns {*}
 */
export function put(id, data) {
  return model.updateByKey(id, formatData(schema.baseFields(), data));
}

/**
 * 删除
 * @param id
 * @returns {*}
 */
export function del(id) {
  return model.deleteByKey(id);
}

/**
 * 列表分页
 * @param page
 * @param number
 * @returns {*}
 */
export function search(where, page = 1, number = 50, order = 'id', direction = 'desc') {
  return model.findListAndCount(where, page, number, `\`${order}\` ${direction}`);
}

export function list(page, number, order, direction) {
  return search([], page, number, order, direction);
}

export function listByLast(robot_id, user_id, max_id, feature, number) {
  let where = [];
  where.push(['robot_id', '=', robot_id]);
  where.push(['feature', '=', feature]);
  where.push(`user_id = "${user_id}" or user_id = 0`);
  if (max_id) where.push(['id', '<', max_id]);
  return model.findByQuery({
    where,
    limit: [0, number],
    order: 'create_time desc',
  });
}
